package com.service.risk;

import com.domain.chart.HighChartData;
import com.domain.page.PageDto;
import com.domain.page.Paginator;
import com.dto.statistic.StatisticOutputDto;
import com.google.common.collect.Maps;
import com.mapper.generator.ShRiskUserMapper;
import com.mapper.self.RiskUserMapper;
import com.task.risk.RiskExcelImportTask;
import com.domain.HttpResponse;
import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.pojo.ShRiskUser;
import com.utils.ConfigUtils;
import com.utils.DateUtils;
import com.utils.ExcelUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/1/10 0010.
 */
@Service(value = "riskService")
public class RiskServiceImpl implements RiskService {
    @Autowired
    private Gson gson;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private RiskUserMapper riskUserMapper;
    @Autowired
    private ShRiskUserMapper shRiskUserMapper;


    @Override
    public Object importExcel(CommonsMultipartFile file) {

        if (file.isEmpty()) {
            return HttpResponse.create(Codes.ExcelParseError);
        }
        String OriginalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(OriginalFilename)) {
            throw BizException.create(Codes.ExcelTypeError, "xls/xlsx");
        }
        FileItem fileItem = file.getFileItem();
        if (!"xls".endsWith(OriginalFilename.substring(
                OriginalFilename.lastIndexOf(".") + 1).toLowerCase()) && !"xlsx".endsWith(OriginalFilename.substring(
                OriginalFilename.lastIndexOf(".") + 1).toLowerCase())) {
            throw BizException.create(Codes.ExcelTypeError, "xls/xlsx");
        }
        List<ShRiskUser> userList = Lists.newArrayList();
        List<List<String>> list = null;
        try {
            list = ExcelUtils.importExcel((fileItem.getInputStream()));
            if (CollectionUtils.isEmpty(list)) {
                return userList;
            }
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                List<String> subList = (List) iterator.next();
                if (CollectionUtils.isEmpty(subList)) {
                    continue;
                }
                ShRiskUser shRiskUser = new ShRiskUser();
                shRiskUser.setDeleted(0);
                shRiskUser.setCreatetime(DateUtils.currentTime());
                if (subList.size() > 0) {
                    if (StringUtils.isNotBlank(subList.get(0))) {
                        shRiskUser.setJoinTime(getDateValue(Double.valueOf(subList.get(0))));
                    }
                }
                if (subList.size() > 1) {
                    shRiskUser.setName(subList.get(1));
                }
                if (subList.size() > 2) {
                    shRiskUser.setMobile(subList.get(2));
                }
                if (subList.size() > 3) {
                    shRiskUser.setRent(subList.get(3));
                }
                if (subList.size() > 4) {
                    shRiskUser.setPayType(subList.get(4));
                }
                if (subList.size() > 5) {
                    shRiskUser.setCity(subList.get(5));
                }
                if (subList.size() > 6) {
                    shRiskUser.setIsGraduated(subList.get(6));
                }
                if (subList.size() > 7) {
                    shRiskUser.setSchool(subList.get(7));
                }
                if (subList.size() > 8) {
                    if (StringUtils.isNotBlank(subList.get(8))) {
                        shRiskUser.setGraduationDate(getDateValue(Double.valueOf(subList.get(8))));
                    }
                }
                if (subList.size() > 9) {
                    shRiskUser.setEducation(subList.get(9));
                }
                if (subList.size() > 10) {
                    shRiskUser.setCompany(subList.get(10));
                }
                if (subList.size() > 11) {
                    if (StringUtils.isNotBlank(subList.get(11))) {
                        shRiskUser.setEntryTime(getDateValue(Double.valueOf(subList.get(11))));
                    }
                }
                if (subList.size() > 12) {
                    shRiskUser.setJob(subList.get(12));
                }
                if (subList.size() > 13) {
                    shRiskUser.setIncome(subList.get(13));
                }
                if (subList.size() > 14) {
                    shRiskUser.setExpense(subList.get(14));
                }
                if (subList.size() > 15) {
                    shRiskUser.setQq(subList.get(15));
                }
                if (subList.size() > 16) {
                    shRiskUser.setAuthSesame(subList.get(16));
                }
                userList.add(shRiskUser);
            }
        } catch (IOException e) {
            return HttpResponse.create(Codes.ExcelParseError, e.getMessage());
        }


        // - 导入文件后通过EventBus发消息将数据入库

//    EventBus eventBus = new EventBus("TestEventBus");
//    eventBus.register(new RiskExcelImportListener());
//    eventBus.post(userList);

        RiskExcelImportTask riskExcelImportTask = new RiskExcelImportTask();
        riskExcelImportTask.setList(userList);
        threadPoolTaskExecutor.execute(riskExcelImportTask);
        return HttpResponse.create(Codes.OK, "导入完成", userList);
    }


    /**
     * 模版下载
     *
     * @return
     */
    @Override
    public Object downTemplate() {

        String temp = ConfigUtils.getString("risk.excel.export.template");
        if (StringUtils.isBlank(temp)) {
            throw BizException.create(Codes.TemplateExportError, "没有检测到表头");
        }
        Collection<String> title = Arrays.asList(temp.split(","));

        return ExcelUtils.exportExcel(null, title, "Template.xls");
    }

    /**
     * 返回时间内的特殊时间格式 OFFICE2003
     *
     * @param val
     * @return
     */
    private static String getDateValue(Double val) {
        Date date = new Date(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = HSSFDateUtil.getJavaDate(val);
        return simpleDateFormat.format(date);
    }


    /**
     * 导出所有数据到Excel
     *
     * @return
     */
    @Override
    public Object exportExcel() {
        String temp = ConfigUtils.getString("risk.excel.export.title");
        if (StringUtils.isBlank(temp)) {
            throw BizException.create(Codes.TemplateExportError, "没有检测到表头");
        }
        Collection<String> title = Arrays.asList(temp.split(","));

        Collection<ShRiskUser> list = riskUserMapper.query(null, null, null);

        String fileName = "ExportExcel[" + DateUtils.now() + "].xls";
        return ExcelUtils.exportExcel(list, title, fileName);
    }

    /**
     * 批量插入/更新
     *
     * @param list
     * @return
     */
    @Override
    public int batchSaveOrUpdate(List<ShRiskUser> list) {

        return riskUserMapper.batchSaveOrUpdate(list);
    }


    // - 模糊查询
    @Override
    public Object query(PageDto pageDto) {

        if (StringUtils.isNotBlank(pageDto.getKey())) {
            if (pageDto.getKey().indexOf("'") > 0) {
                pageDto.setKey(pageDto.getKey().replace("'", "\\'"));
            }
        }

        List<ShRiskUser> list = riskUserMapper.query(pageDto.getKey(), (pageDto.getPage() - 1) * pageDto.getLimit(), pageDto.getLimit());
        if (list == null) {
            list = Lists.newArrayList();
        }
        int totalCount = riskUserMapper.queryTotalCount(pageDto.getKey());
        return Paginator.instance(totalCount, list);
    }


    // - 根据主键删除
    @Override
    public Object batchDel(Integer[] idArr) {
        int ret = riskUserMapper.batchDel(idArr);
        return HttpResponse.OK();
    }


    /**
     * 时域统计
     *
     * @param type year,month,day
     * @return
     */
    @Override
    public HighChartData timeStatistic(String type) {


        List<StatisticOutputDto> list = Lists.newArrayList();

        Map<String, BigDecimal> map = Maps.newHashMap();
        if ("year".equals(type)) {
            // - 年
            for (int i = 0; i < 10; i++) {
                map.put(String.valueOf(DateUtils.getYear() - i), BigDecimal.ZERO);
            }
        } else if ("month".equals(type)) {
            // - 月
            for (int i = 1; i < 13; i++) {
                map.put(String.valueOf(i), BigDecimal.ZERO);
            }
        } else if ("day".equals(type)) {
            // - 日
            for (int i = 1; i < 25; i++) {
                map.put(String.valueOf(i), BigDecimal.ZERO);
            }
        }


        if ("year".equals(type)) {
            list = riskUserMapper.yearStatistic();
        } else if ("month".equals(type)) {
            list = riskUserMapper.monthStatistic();
        } else if ("day".equals(type)) {
            list = riskUserMapper.dayStatistic();
        }
        HighChartData highChartData = new HighChartData();
        if (!CollectionUtils.isEmpty(list)) {
            List<String> xAixs = Lists.newArrayList();
            List<BigDecimal> series = Lists.newArrayList();
            for (StatisticOutputDto statisticOutputDto : list) {
                map.put(statisticOutputDto.getName(), statisticOutputDto.getData());
            }
            for (String key:map.keySet()){
                xAixs.add(key);
            }
            // - 排序
            Collections.sort(xAixs, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
                }
            });
            for (String temp:xAixs){
                series.add(map.get(temp));
            }


            if ("month".equals(type)){
                for (int i=0;i<xAixs.size();i++){
                    if (Integer.valueOf(xAixs.get(i)) < 10){
                        xAixs.set(i,"0"+xAixs.get(i));
                    }
                }
            }

            if ("day".equals(type)){
                for (int i=0;i<xAixs.size();i++){
                    xAixs.set(i,xAixs.get(i)+":00");
                }
            }
            highChartData.setxAixs(xAixs);
            highChartData.setSeries(series);
        }

        return highChartData;
    }
}
